package com.wdj.creation.singleton.CASSingtelon;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName Singtelong
 * @Description
 * @Author wdj
 * @Date 2020/8/22 11:15
 * @Version 1.0
 **/
public class Singleton {
    private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();


    private Singleton(){}
    /*
    * 用CAS确保线程安全
    * */
    public static final Singleton getInstance(){
        for(;;){
            Singleton current = INSTANCE.get();
            if (current != null){
                return  current;
            }
            current = new Singleton();
            if (INSTANCE.compareAndSet(null, current)){
                return current;
            }
        }
    }
    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2);
    }

}
